package com.nf.health.app.datamain.activity;

import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nf.health.app.BleThirdLib.utils.HexUtil;
import com.nf.health.app.R;
import com.nf.health.app.customview.SweatShowView;
import com.nf.health.app.models.UserInfo;
import com.nf.health.app.utils.DeviceUUID;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by nf on 17/4/18.
 */

public class MeasureHeartRateActivity extends MeasureBaseAcitivity {
    TextView tv_timeCount;
    Button btn_timeStart;
    StartMeasureTimeCount startMeasureTimeCount;//倒计时
    private int current_count;//存储现在开始第几次测量

    private boolean isStartTest;

    private int heartrate_quiet = 100;//安静心率
    private int heartrate_first = 0;//第一次心率
    private int heartrate_second = 0;//2
    private int heartrate_third = 0;//第三次
    //心率折线相关
    SweatShowView view_show_heart_rate;
    List<Float> mHeartrateDataList = new ArrayList<>();
    private ImageView mTitlebarRightView;

    //检测蓝牙是否正常开启
    private class StartMeasureTimeCount extends CountDownTimer {
        public StartMeasureTimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            tv_timeCount.setText((l / 1000) / 60 + ":" + ((l / 1000) % 60));
            if (tv_timeCount.getText().equals("0:1")) {
                tv_timeCount.setText("0:0");
            }
        }

        @Override
        public void onFinish() {
            isStartTest = false;
            btn_timeStart.setText("开始测量");
        }
    }

    @Override
    public void write_device(byte[] command) {
        super.write_device(command);
    }

    @Override
    protected void initDefaultConfig() {
        setTitleBar(R.layout.layout_common_header);
        setContent(R.layout.activity_datameasure_heartrate);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "心率带数据");
//        ViewUtil.setImageResoure(this, R.id.titlebar_right_view, R.drawable.ic_title_setting);
//        mTitlebarRightView = (ImageView)findViewById(R.id.titlebar_right_view);
//        mTitlebarRightView.setOnClickListener(this);
        view_show_heart_rate = (SweatShowView) findViewById(R.id.view_show_heart_rate);
        //tv_right_view = (TextView) findViewById(R.id.tv_right_view);
        tv_timeCount = (TextView) findViewById(R.id.tv_time_count);
        btn_timeStart = (Button) findViewById(R.id.btn_time_start);
        //tv_right_view.setText("保存");
        //tv_right_view.setVisibility(View.VISIBLE);

        btn_timeStart.setOnClickListener(this);
        //tv_right_view.setOnClickListener(this);

        current_count = 0;
        startMeasureTimeCount = new StartMeasureTimeCount(10000, 1000);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() != R.id.btn_time_start) {
            if (isStartTest) {
                Toast.makeText(context, "正在进行测量!", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        switch (v.getId()) {
            case R.id.btn_time_start:
                startMeasure();
            break;

//            case R.id.tv_right_view: {
//                if (heartrate_first > 0 && heartrate_second > 0) {
//                    upLoadMeasureFinishData();
//
//                } else {
//                    Toast.makeText(context, "未检测到数据!", Toast.LENGTH_SHORT).show();
//                }
//            }
//            break;
        }
    }

    @Override
    protected int DEVICE_TYPE() {
        return DeviceUUID.HeartRateType;
    }

    @Override
    protected byte[] sendOrderData() {
        return new byte[0];
    }

    @Override
    protected void receivedDataAnalyse(byte[] data) {
        Log.e("接收到数据", HexUtil.encodeHexStr(data));
        mDialogManager.hideAllDialog();

        if (data.length >= 2 && data.length < 6) {
            if (data[0] == 0x06 || data[0] == 0x04) {

                int heartRate = data[1];
                heartRate = Math.abs(heartRate);
                showHeartRate(heartRate);
                if (current_count == 0) {
                    if (heartrate_quiet < heartRate) {
                        heartrate_quiet = heartRate;
                    }
                    //Toast.makeText(context, "实时心率:" + heartRate, Toast.LENGTH_SHORT).show();
                    final int finalHeartRate = heartRate;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            tv_timeCount.setText(finalHeartRate +"");
                        }
                    });
                }

                String hint = "<font color='#A9A6A2'>" + "最大心率" + "</font>"
                        + "<strong><font color='#FC9709'>" + "" + heartRate + "</font><strong>"
                        + "<font color='#A9A6A2'>" + "次/分钟" + "</font>";

                if (current_count == 1 && isStartTest) {
                    if (heartrate_first < heartRate) {
                        heartrate_first = heartRate;
                        //tv_rate_1.setText(Html.fromHtml(hint));
                    }

                } else if (current_count == 2 && isStartTest) {
                    if (heartrate_second < heartRate) {
                        heartrate_second = heartRate;
                        //tv_rate_2.setText(Html.fromHtml(hint));

                        if (heartrate_first < heartrate_second) {

                            UserInfo entry = PreferenceHelper.getUser();
                            int age = 30;
                            boolean man = entry.getSex().equals("1");
                            String birthday = entry.getBirthday();
                            if (!TextUtils.isEmpty(birthday)) {
                                age = Calendar.getInstance().get(Calendar.YEAR) - Integer.valueOf(birthday.substring(0, 4));
                            }

                            int ec1 = 4, ec2 = 6, ec3 = 8;
                            if (man) {
                                if (age < 50) {
                                    ec1 = 5;
                                    ec2 = 7;
                                    if (age < 40) {
                                        ec3 = 10;
                                    } else {
                                        ec3 = 9;
                                    }
                                }
                            } else {
                                if (age >= 50) {
                                    ec1 = 3;
                                    ec2 = 5;
                                    ec3 = 7;
                                }
                            }


                            double maxth = (ec2 - ec1) / (heartrate_second - heartrate_first) * (206.9 - 0.7 * 34 - heartrate_first) + ec1;
                            //heartrate_second_ad = maxth + "";
                            String heart = "<font color='#A9A6A2'>" + "心脏功能能力" + "</font>"
                                    + "<strong><font color='#FC9709'>" + "" + Math.round(maxth) + "</font><strong>"
                                    + "<font color='#A9A6A2'>" + "次/分钟" + "</font>";

                            //tv_rate_3.setText(Html.fromHtml(heart));
                        }
                    }
                } else if (current_count == 3 && isStartTest) {
                    if (heartrate_third < heartRate) {
                        heartrate_third = heartRate;
                        //tv_rate_4.setText(Html.fromHtml(hint));

                        if (heartrate_second < heartrate_third) {

                            UserInfo entry = PreferenceHelper.getUser();
                            int age = 30;
                            boolean man = entry.getSex().equals("1");
                            String birthday = entry.getBirthday();
                            if (!TextUtils.isEmpty(birthday)) {
                                age = Calendar.getInstance().get(Calendar.YEAR) - Integer.valueOf(birthday.substring(0, 4));
                            }

                            int ec1 = 4, ec2 = 6, ec3 = 8;
                            if (man) {
                                if (age < 50) {
                                    ec1 = 5;
                                    ec2 = 7;
                                    if (age < 40) {
                                        ec3 = 10;
                                    } else {
                                        ec3 = 9;
                                    }
                                }
                            } else {
                                if (age >= 50) {
                                    ec1 = 3;
                                    ec2 = 5;
                                    ec3 = 7;
                                }
                            }

                            double maxth = (ec3 - ec2) / (heartrate_third - heartrate_second) * (206.9 - 0.7 * 34 - heartrate_second) + ec2;
                            //heartrate_third_ad = maxth + "";
                            String heart = "<font color='#A9A6A2'>" + "心脏功能能力" + "</font>"
                                    + "<strong><font color='#FC9709'>" + "" + Math.round(maxth) + "</font><strong>"
                                    + "<font color='#A9A6A2'>" + "次/分钟" + "</font>";
                            //tv_rate_5.setText(Html.fromHtml(heart));
                        }

                    }
                }

            }
        }

    }


    private void showHeartRate(int heartRate) {
        mHeartrateDataList.add(Float.valueOf(heartRate));
        //去掉多余缓存
        int size = mHeartrateDataList.size();
        if (size > 50) {
            mHeartrateDataList = mHeartrateDataList.subList(size - 30, size);
        }
        view_show_heart_rate.setDataList(mHeartrateDataList);
    }

    @Override
    protected void upLoadMeasureFinishData() {
        showDialog("提示", "测量完成,正在上传数据...");
       // UserInfo userInfo = PreferenceHelper.getUser(context);
       // provider.getSendHeartData(userInfo.getUserid(), userInfo.getUserno(), heartrate_quiet + "", heartrate_first + "", heartrate_second + "", heartrate_second_ad, +heartrate_third + "", heartrate_third_ad);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (startMeasureTimeCount != null) {
            startMeasureTimeCount.cancel();
        }
    }
}
















